import { useRequest } from 'ahooks'
import type { Options } from 'ahooks/lib/useRequest/src/types'
import axios from 'axios'

import './__mock__'

/** 国家 */
export interface ICountry {
  id: number
  code: string
  chineseName: string
}

export interface TCountriesRes {
  list: ICountry[]
  idMap: Record<number, ICountry | undefined>
  codeMap: Record<string, ICountry | undefined>
}

/** SWR 获取国家列表 */
export const useCountries = (opts?: Options<TCountriesRes, []>) => {
  return useRequest<TCountriesRes, []>(
    async () => {
      const res = await axios.get(`/api/admin/countries/all`)
      const list: ICountry[] = res.$data || []
      const idMap = list.reduce((o, i) => ({ ...o, [i.id]: i }), {})
      const codeMap = list.reduce((o, i) => ({ ...o, [i.code]: i }), {})
      return { list, idMap, codeMap }
    },
    {
      cacheTime: -1, // 永不过期
      staleTime: -1, // 永远新鲜
      ...opts,
      cacheKey: 'SWRApi_useCountries',
    },
  )
}
